package com.tju.welding.service.impl;

import javax.servlet.http.HttpSession;

import com.tju.welding.dao.UserMapper;
import com.tju.welding.pojo.User;
import com.tju.welding.service.UserService;
import com.tju.welding.utils.ApiResponse;
import com.tju.welding.utils.Code;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public ApiResponse register(String realName, String password, int userType, String phoneNumber) {
        try {
            User temp = userMapper.getUserByPhoneNumber(phoneNumber);
            if (temp != null)
                return ApiResponse.error(Code.PHONE_NUMBER_EXISTED);
            else {
                userMapper.addUser(password, realName, phoneNumber, userType);
                return ApiResponse.success("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(Code.SERVER_ERROR);
        }
    }

    @Override
    public ApiResponse login(String phoneNumber, String password, HttpSession session) {
        try {
            User temp = userMapper.getUserByPhoneNumber(phoneNumber);
            if (temp == null)
                return ApiResponse.error(Code.PHONE_NUMBER_NOT_EXISTED);
            else {
                if (temp.getPassword().equals(password)){
                    session.setAttribute("user", temp);
                    return ApiResponse.success("ok");
                }
                else
                    return ApiResponse.error(Code.PASSWOED_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(Code.SERVER_ERROR);
        }
    }

    @Override
    public ApiResponse logout(HttpSession session) {
        try {
            session.removeAttribute("user");
            return ApiResponse.success("ok");
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(Code.SERVER_ERROR);
        }
    }

}
